package com.cxyd.greenSite.utils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


public class WeatherUtil2 {

    //获取未来三天天气
    public static Map<String, Object> getForecastWeather(String Cityid) throws IOException, NullPointerException {
        // 连接和风天气的API
        String url1= "https://free-api.heweather.net/s6/weather/forecast?location="+Cityid+"&key=3c3fa198cacc4152b94b20def11b2455";

        StringBuffer stringBuffer = null;// 相当于一个 字符串，只不过线程更安全
        Map<String, Object> map = new HashMap<String, Object>();
        InputStream inputStream = null;// 获取要输入的数据
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;
        try{
            URL url = new URL(url1);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            if (httpURLConnection.getResponseCode() == 200) {
                // 接收结果
                inputStream = httpURLConnection.getInputStream();
            } else {
                // 检测网络异常
                map.put("error",11);
                return map;
            }
            reader = new InputStreamReader(inputStream, "UTF-8");// 读取输入的数据，解决乱码
            bufferedReader = new BufferedReader(reader);// 缓存流
            stringBuffer = new StringBuffer();
            String timp = null;
            // 缓冲逐行读取
            while ((timp = bufferedReader.readLine()) != null) {
                stringBuffer.append(timp);
            }

            String s = stringBuffer.toString(); //转为json字符串
            //JSONObject object = new JSONObject(s);//new JSONObject(s)只能接收boolean类型的参数?
            JSONObject object = JSONObject.fromObject(s);
            JSONObject object1 = object.getJSONArray("HeWeather6").getJSONObject(0);

            //基础信息
            JSONObject basic = object1.getJSONObject("basic");
            //接口更新时间
            JSONObject update = object1.getJSONObject("update");
            //天气预报
            JSONArray daily_forecast = object1.getJSONArray("daily_forecast");

            //基础信息
            map.put("location",basic.getString("location").toString());//城市名称
            map.put("parent_city",basic.getString("parent_city").toString());//该城市的上级城市
            map.put("admin_area",basic.getString("admin_area").toString());//所属行政区域
            map.put("cnty",basic.getString("cnty").toString());//所属国家

            //接口更新时间
            String time = update.getString("loc").toString();
            String week = strToDate(time);
            map.put("week",week);
            map.put("time",update.getString("loc").toString());


            //今天的天气
            Map<String, Object> today = new HashMap<String, Object>();
            today.put("date",daily_forecast.getJSONObject(0).getString("date"));//日期
            today.put("cond_txt_d",daily_forecast.getJSONObject(0).getString("cond_txt_d"));//白天天气状况描述
            today.put("cond_txt_n",daily_forecast.getJSONObject(0).getString("cond_txt_n"));//晚间天气状况描述
            today.put("wind_dir",daily_forecast.getJSONObject(0).getString("wind_dir"));//风向
            today.put("wind_sc",daily_forecast.getJSONObject(0).getString("wind_sc"));//风力
            today.put("wind_spd",daily_forecast.getJSONObject(0).getString("wind_spd"));//风速
            today.put("vis",daily_forecast.getJSONObject(0).getString("vis"));//能见度
            today.put("tmp_max",daily_forecast.getJSONObject(0).getString("tmp_max"));//最高温度
            today.put("tmp_min",daily_forecast.getJSONObject(0).getString("tmp_min"));//最低温度
            today.put("hum",daily_forecast.getJSONObject(0).getString("hum"));//相对湿度

            //明天的天气
            Map<String, Object> tomorrow = new HashMap<String, Object>();
            tomorrow.put("date",daily_forecast.getJSONObject(1).getString("date"));//日期
            tomorrow.put("cond_txt_d",daily_forecast.getJSONObject(1).getString("cond_txt_d"));//白天天气状况描述
            tomorrow.put("cond_txt_n",daily_forecast.getJSONObject(1).getString("cond_txt_n"));//晚间天气状况描述
            tomorrow.put("wind_dir",daily_forecast.getJSONObject(1).getString("wind_dir"));//风向
            tomorrow.put("wind_sc",daily_forecast.getJSONObject(1).getString("wind_sc"));//风力
            tomorrow.put("wind_spd",daily_forecast.getJSONObject(1).getString("wind_spd"));//风速
            tomorrow.put("vis",daily_forecast.getJSONObject(1).getString("vis"));//能见度
            tomorrow.put("tmp_max",daily_forecast.getJSONObject(1).getString("tmp_max"));//最高温度
            tomorrow.put("tmp_min",daily_forecast.getJSONObject(1).getString("tmp_min"));//最低温度
            tomorrow.put("hum",daily_forecast.getJSONObject(1).getString("hum"));//相对湿度

            //后天的天气
            Map<String, Object> dayaftertomorrow = new HashMap<String, Object>();
            dayaftertomorrow.put("date",daily_forecast.getJSONObject(2).getString("date"));//日期
            dayaftertomorrow.put("cond_txt_d",daily_forecast.getJSONObject(2).getString("cond_txt_d"));//白天天气状况描述
            dayaftertomorrow.put("cond_txt_n",daily_forecast.getJSONObject(2).getString("cond_txt_n"));//晚间天气状况描述
            dayaftertomorrow.put("wind_dir",daily_forecast.getJSONObject(2).getString("wind_dir"));//风向
            dayaftertomorrow.put("wind_sc",daily_forecast.getJSONObject(2).getString("wind_sc"));//风力
            dayaftertomorrow.put("wind_spd",daily_forecast.getJSONObject(2).getString("wind_spd"));//风速
            dayaftertomorrow.put("vis",daily_forecast.getJSONObject(2).getString("vis"));//能见度
            dayaftertomorrow.put("tmp_max",daily_forecast.getJSONObject(2).getString("tmp_max"));//最高温度
            dayaftertomorrow.put("tmp_min",daily_forecast.getJSONObject(2).getString("tmp_min"));//最低温度
            dayaftertomorrow.put("hum",daily_forecast.getJSONObject(2).getString("hum"));//相对湿度

            map.put("today",today);
            map.put("tomorrow",tomorrow);
            map.put("dayaftertomorrow",dayaftertomorrow);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
                if(reader!=null){
                    reader.close();
                }
                if(bufferedReader!=null){
                    bufferedReader.close();
                }

            } catch ( Exception  e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    //获取pm2.5信息
    public static Map<String, Object> getPM25(String Cityid) throws IOException, NullPointerException {
        // 连接和风天气的API
        String url1= "https://free-api.heweather.net/s6/air/now?location="+Cityid+"&key=3c3fa198cacc4152b94b20def11b2455";

        StringBuffer stringBuffer = null;// 相当于一个 字符串，只不过线程更安全
        Map<String, Object> map = new HashMap<String, Object>();
        InputStream inputStream = null;// 获取要输入的数据
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;
        try{
            URL url = new URL(url1);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            if (httpURLConnection.getResponseCode() == 200) {
                // 接收结果
                inputStream = httpURLConnection.getInputStream();
            } else {
                // 检测网络异常
                map.put("error",11);
                return map;
            }
            reader = new InputStreamReader(inputStream, "UTF-8");// 读取输入的数据，解决乱码
            bufferedReader = new BufferedReader(reader);// 缓存流
            stringBuffer = new StringBuffer();
            String timp = null;
            // 缓冲逐行读取
            while ((timp = bufferedReader.readLine()) != null) {
                stringBuffer.append(timp);
            }

            String s = stringBuffer.toString(); //转为json字符串
            //JSONObject object = new JSONObject(s);//new JSONObject(s)只能接收boolean类型的参数?
            JSONObject object = JSONObject.fromObject(s);
            JSONObject object1 = object.getJSONArray("HeWeather6").getJSONObject(0);

            //基础信息
            JSONObject basic = object1.getJSONObject("basic");
            //接口更新时间
            JSONObject update = object1.getJSONObject("update");
            //天气预报
            JSONObject air_now_city = object1.getJSONObject("air_now_city");

            //基础信息
            map.put("location",basic.getString("location").toString());//城市名称
            map.put("parent_city",basic.getString("parent_city").toString());//该城市的上级城市
            map.put("admin_area",basic.getString("admin_area").toString());//所属行政区域
            map.put("cnty",basic.getString("cnty").toString());//所属国家

            //接口更新时间
            String time = update.getString("loc").toString();
            String week = strToDate(time);
            map.put("week",week);
            map.put("time",update.getString("loc").toString());

            //空气质量实况（城区）
            map.put("pub_time",air_now_city.getString("pub_time"));//数据发布时间,格式yyyy-MM-dd HH:mm
            map.put("aqi",air_now_city.getString("aqi"));//空气质量指数，AQI和PM25的关系
            map.put("qlty",air_now_city.getString("qlty"));// 	空气质量，取值范围:优，良，轻度污染，中度污染，重度污染，严重污染，查看计算方式
            map.put("pm10",air_now_city.getString("pm10"));//pm10
            map.put("pm25",air_now_city.getString("pm25"));//pm25
            map.put("so2",air_now_city.getString("so2"));//so2
            map.put("co",air_now_city.getString("co"));//co

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭流
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
                if(reader!=null){
                    reader.close();
                }
                if(bufferedReader!=null){
                    bufferedReader.close();
                }

            } catch ( Exception  e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 时间获得星期
     * @param strDate
     * @return
     * @throws ParseException
     */
    public static String strToDate(String strDate) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(formatter.parse(strDate));
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
        String week = sdf.format(c.getTime());
        return week;
    }

    /**
     * 字符集转码
     * @param url
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String urlEncode(String url) throws UnsupportedEncodingException {
        if(url == null) {
            return null;
        }

        final String reserved_char = ";/?:@=&";
        String ret = "";
        for(int i=0; i < url.length(); i++) {
            String cs = String.valueOf( url.charAt(i) );
            if(reserved_char.contains(cs)){
                ret += cs;
            }else{
                ret += URLEncoder.encode(cs, "utf-8");
            }
        }
        return ret.replace("+", "%20");
    }

    public static void main(String[] args) {
        try {
            //Map<String, Object> m = getForecastWeather("北京");
            Map<String, Object> pm25 = getPM25("武汉");
            System.out.println(pm25);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
